Developing a RESTful API with Go and Gin

  • Using package gin
package main

import (
  "net/http"
  "github.com/gin-gonic/gin"
)

// Struct tags such as json:"artist" specify what a field’s name should be when the struct’s contents are serialized into JSON. Without them, the JSON would use the struct’s capitalized field names – a style not as common in JSON.
type album struct {
  ID string `JSON:"id"`
  Title string `JSON:"title"`
  Artist string `JSON:"artist"`
  Price float32 `JSON:"price"`
}

var albums = []album{
	{ID: "1", Title: "Blue Train", Artist: "John Coltrane", Price: 56.99},
	{ID: "2", Title: "Jeru", Artist: "Gerry Mulligan", Price: 17.99},
	{ID: "3", Title: "Sarah Vaughan and Clifford Brown", Artist: "Sarah Vaughan", Price: 39.99},
}

func main() {
  router := gin.Default()
	router.GET("/", getAlbums)
	router.GET("/:id", getAlbumById)
	router.POST("/", addAlbum)

	router.Run("localhost:8080")
}

func getAlbums(c *gin.Context) {
  return c.IndentedJSON(http)
}

func addAlbum(c *gin.Context) {
	var newAlbum album

	if err := c.BindJSON(&newAlbum); err != nil {
		return
	}

	albums = append(albums, newAlbum)
	c.IndentedJSON(http.StatusOK, newAlbum)
}

func getAlbumById(c *gin.Context) {
	id := c.Param("id")

	for _, item := range albums {
		if item.ID == id {
			c.IndentedJSON(http.StatusOK, item)
			return
		}
	}

	c.IndentedJSON(http.StatusOK, gin.H{"message": "album not found"})
}